(function(angular) {
	'use strict';
	angular.module('fs.waf').directive('fsDashboardDraggable', fsDashboardDraggable).provider('dashboardPanelService', dashboardPanelServiceProvider);

	fsDashboardDraggable.$inject = [ '$document', '$timeout', 'storageService' ];
	function fsDashboardDraggable($document, $timeout, storageService) {
		return {
			restrict : 'A',
			link : function($scope, element, $attrs, ctrls) {
			}
		};
	}

	dashboardPanelServiceProvider.$inject = [];
	function dashboardPanelServiceProvider() {
		var provider = this;
		provider.panelConfigs = {};
		provider.loadingCount = 0;
		provider.loadingInstance = null;
		provider.setpanelConfig = function(name, options) {
			provider.panelConfigs[name] = options;
		};
		provider.panelOptions = {
			size : 'lg',
			blocked : false,
			backdrop : false,
			keyboard : false,
			animation : false
		// windowTemplateUrl : 'pti/template/modal/window.html',
		// appendTo : provider.appendTo,
		// scope : provider.scope
		// backdropClass: '',
		// controller: '',
		// controllerAs: '',
		// openedClass:'',
		// resolve:{},
		// template: '',
		// templateUrl: '',
		// windowClass: '',
		// resolve : object or function
		};
		provider.$get = dashboardPanelService;
		dashboardPanelService.$inject = [ '$rootScope', '$stateParams', '$ocLazyLoad', '$uibModal', '$uibPosition', '$window', '$document', '$q', '$log', '$timeout', 'Constants', 'modalService', 'routerService', 'ajaxServiceFactory', 'storageService', '$filter' ];
		function dashboardPanelService($rootScope, $stateParams, $ocLazyLoad, $uibModal, $uibPosition, $window, $document, $q, $log, $timeout, Constants, modalService, routerService, ajaxServiceFactory, storageService, $filter) {
			var log = $log.getInstance('dashboardPanelService');
			provider.panelOptions.scope = $rootScope;
			function showPanelHelp(panelConfig) {
				if (panelConfig) {
					if ($rootScope.helpDialog && $rootScope.helpDialog.close) {
						$rootScope.helpDialog.close();
					}
					$rootScope.helpDialog = modalService.openInfoDialogs({
						'messages' : panelConfig.helpMessages
					});
				}
			}
			function removePanel(panelConfig) {
				if (panelConfig) {
					panelConfig.isRemoved = true;
					panelConfig.pageConfig.hasRemoved = true;
					storageService.saveDbdPanelSetting(panelConfig.pagePanelId, {
						isRemoved : true
					});
				}
				if (panelConfig.panelInstance) {
					panelConfig.panelInstance.close();
				}
			}
			function addPanel(panelConfig) {
				var panelInstance, promise;
				loadDependentFiles(panelConfig).then(function(response) {
					if (response.panelViewLinkurls && response.panelViewLinkurls.data) {
						$stateParams.authorization = buildAuthService($rootScope, Constants, ajaxServiceFactory, response.panelViewLinkurls.data || {});
					}
					if (response.panelViewRes && response.panelViewRes.data) {
						var resources = storageService.getItemFromSession(Constants.SESSION_I18N_RESOURES);
						if (response.panelViewRes.data) {
							if(resources != null){
								angular.merge(resources, response.panelViewRes.data)
							} else {
								resources = response.panelViewRes.data;
							}
							if (resources) {
								storageService.setItemToSession(Constants.SESSION_I18N_RESOURES, resources);
								$rootScope.$emit(Constants.NOTIFY_CHANGE_LANGUAGE);
							}
						}
					}
					if (response.panelViewValidate && response.panelViewValidate.data) {
						var resources = storageService.getItemFromSession(Constants.SESSION_I18N_RESOURES);
						if (response.panelViewValidate.data.resources) {
							if(resources != null){
								angular.merge(resources, response.panelViewValidate.data.resources)
							} else {
								resources = response.panelViewValidate.data.resources;
							}
							if (resources) {
								storageService.setItemToSession(Constants.SESSION_I18N_RESOURES, resources);
								$rootScope.$emit(Constants.NOTIFY_CHANGE_LANGUAGE);
							}
						}
					}
					panelConfig.bodyStyle = {
						width : '100%',
						height : (panelConfig.minHeight) + 'px',
						'overflow' : 'hidden'
					};
					panelConfig.dashboardTemplateUrl = panelConfig.panelViewTemplate.replace('${theme}', routerService.getTheme());
					var panelOptions = angular.extend({
						appendTo : angular.element($document[0].querySelector('#' + panelConfig.panelCode + $filter('encode')(panelConfig.pagePanelId))),
						templateUrl : 'pti/template/modal/dashboard/panel.html',
						size : [panelConfig.minWidth, panelConfig.minHeight],
						controller : response.panelViewCtrljs.controller,
						controllerAs : response.panelViewCtrljs.controllerAs,
						windowTopClass : panelConfig.windowTopClass,
						animation : false,
						isDashboard : true,
						resolve : {
							panelConfig : panelConfig,
							layoutConfig : response.panelViewLayout ? response.panelViewLayout.data : null,
							i18nConfig : response.panelViewRes ? response.panelViewRes.data : null,
							authService : $stateParams.authorization,
							validatorConfig : (response.panelViewValidate && response.panelViewValidate.data) ? response.panelViewValidate.data.rules : null
						}
					}, provider.panelOptions);
					panelInstance = $uibModal.open(panelOptions);
					panelConfig.panelInstance = panelInstance;
					panelConfig.isRemoved = false;
					return panelInstance;
				}, function(e) {
					console.log(e);
				});
			}
			
			function buildAuthService($rootScope, Constants, ajaxServiceFactory, authorizationConfig) {
				var authorizationServices = {}, authService, emptyServiceNames = [];
				angular.forEach(authorizationConfig, function(value, key) {
					if (value == '') {
						emptyServiceNames.push(key);
					} else {
						authorizationServices[key] = {
							url : value,
							method : 'post',
							'cache' : provider.cacheAuthorization
						};
					}
				});
				authService = ajaxServiceFactory.buildAjaxService(authorizationServices) || {};
				angular.forEach(emptyServiceNames, function(value, key) {
					authService[value] = angular.noop;
				});
				return authService;
			}

			function loadDependentFiles(panelConfig) {
				var ajaxConfig = {}, promises = {}, ajaxService, defer = $q.defer();
				$ocLazyLoad.load(panelConfig.panelViewCtrljs.replace('${theme}', routerService.getTheme()), {
					cache : true
				}).then(function(response) {
					defer.resolve({
						controller : 'poi.dashboard.' + panelConfig.panelViewCtrljs.split('/').pop().split('.').shift(),
						controllerAs : 'panelController'
					});
				}, function(e) {
					defer.reject(e);
				});
				promises.panelViewCtrljs = defer.promise;
				if (panelConfig.panelViewLayout) {
					ajaxConfig.loadViewConfig = {
						'url' : panelConfig.panelViewLayout.replace('${theme}', routerService.getTheme()),
						'method' : 'get',
						'cache' : false
					};
				}
				if (panelConfig.panelViewRes) {
					ajaxConfig.loadViewRes = {
						'url' : panelConfig.panelViewRes.replace('${theme}', routerService.getTheme()),
						'method' : 'get',
						'cache' : false
					};
				}
				if (panelConfig.panelViewLinkurls) {
					ajaxConfig.loadViewLinkurls = {
						'url' : panelConfig.panelViewLinkurls.replace('${theme}', routerService.getTheme()),
						'method' : 'get',
						'cache' : false
					};
				}
				if (panelConfig.panelViewValidate) {
					ajaxConfig.loadViewValidate = {
						'url' : panelConfig.panelViewValidate.replace('${theme}', routerService.getTheme()),
						'method' : 'get',
						'cache' : false
					};
				}
				ajaxService = ajaxServiceFactory.buildAjaxService(ajaxConfig);
				if (panelConfig.panelViewLayout) {
					promises.panelViewLayout = ajaxService.loadViewConfig();
				}
				if (panelConfig.panelViewRes) {
					promises.panelViewRes = ajaxService.loadViewRes();
				}
				if (panelConfig.panelViewLinkurls) {
					promises.panelViewLinkurls = ajaxService.loadViewLinkurls();
				}
				if (panelConfig.panelViewValidate) {
					promises.panelViewValidate = ajaxService.loadViewValidate();
				}
				return $q.all(promises);
			}
			return {
				addPanel : addPanel,
				removePanel : removePanel,
				showPanelHelp : showPanelHelp
			};
		}
	}

})(angular);
